<template>
   <h1>操作人员添加</h1>
   <el-form :model="addadmin" label-width="120px">
    <el-form-item label="姓名">
      <el-input v-model="addadmin.adminname" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input type="password" v-model="addadmin.password" />
    </el-form-item>
    <el-form-item label="角色">
            <el-radio-group v-model="addadmin.role">
                <el-radio :label="1">超级管理员</el-radio>
                <el-radio :label="2">普通管理员</el-radio>
            </el-radio-group>
        </el-form-item >
        <p style="margin-left: 100px; margin-bottom: 20px;">
            <el-tree ref="treeRef" :data="data" show-checkbox node-key="id" highlight-current />
        </p>
        <el-form-item>
            <el-popconfirm title="亲，感谢您的添加" @confirm="addAdmin">
                    <template #reference>
                        <el-button type="primary">添加</el-button>
                    </template>
                </el-popconfirm>
            
        </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { reactive ,ref} from 'vue';
import { admin_admin_add } from "../../../utils/api";
import {ElNotification}  from 'element-plus'
import "element-plus/es/components/notification/style/css"
import { useRouter } from 'vue-router';
// 树形结构图
import {menudata as data} from "../../../grants/menudata"
const $router = useRouter();

// 定义类型
interface IAdmin {
    "adminname": string,
    "password": string,
    "role": number,  //1:表示超级管理员，2：普通管理员
    "checkedKeys": string[]
}
// 当前管理员的数据
const addadmin = reactive<IAdmin>({
    "adminname": "",
    "password": "",
    "role": 1,
    "checkedKeys": []
});
// 树形结构
const treeRef = ref(null)
// 添加管理员的请求
const addAdmin = ()=>{
  let arr = treeRef.value.getCheckedKeys()   //获取的是选中状态的权限
  let halfarr = treeRef.value.getHalfCheckedKeys()  //半选的权限
  // 拼接两个
  arr = arr.concat(halfarr)
  console.log("arr",arr);
  // 把选中的编号保存到checkedKeys
  addadmin.checkedKeys=arr
  //选中的按钮 会以数组的形式打印出来编号
  // 完善
  // 在添加操作人员的权限时我们如果只选了一级和子一级里边的一项时,发请求时一级不会保存
  // 解决
  // 在树形组件里有一个getHalfCheckedKeys
  if(addadmin.adminname!="" && addadmin.password!=""){
    admin_admin_add(addadmin).then((res: any) => {
  if (res.data.code === "200") {
    ElNotification({
        title:"提示",
        message: "添加成功",
        type: "success",
    })
    // 跳到操作人员列表页面
    $router.push("/admin/listadmin")
  }
})
  }else{
    ElNotification({
        title:"提示",
        message: "请输入内容",
        type: "warning",
    })
  }
}
</script>

<style scoped>
.el-input{
    width: 300px;
}
</style>